package de.ipk_gatersleben.bit.bi.edal.publication.listener;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.rmi.RemoteException;

import javax.swing.JOptionPane;
import javax.swing.text.JTextComponent;

import de.ipk_gatersleben.bit.bi.edal.primary_data.file.PrimaryDataDirectoryException;
import de.ipk_gatersleben.bit.bi.edal.publication.AttributeLabel;
import de.ipk_gatersleben.bit.bi.edal.publication.AttributeTextArea;
import de.ipk_gatersleben.bit.bi.edal.publication.PublicationButtonLinePanel;
import de.ipk_gatersleben.bit.bi.edal.publication.PublicationFrame;
import de.ipk_gatersleben.bit.bi.edal.publication.PublicationMainPanel;
import de.ipk_gatersleben.bit.bi.edal.publication.PublicationModul;
import de.ipk_gatersleben.bit.bi.edal.publication.Utils;
import de.ipk_gatersleben.bit.bi.edal.publication.PropertyLoader;

public class TextAreaValueChangedFocusListener implements FocusListener {

	private AttributeLabel label;
	private JTextComponent textArea;
	private String defaultString;

	public TextAreaValueChangedFocusListener(AttributeLabel label,
			JTextComponent titleArea, String defaultString) {
		this.label = label;
		this.textArea = titleArea;
		this.defaultString = defaultString;
	}

	@Override
	public void focusGained(FocusEvent event) {
		
		label.setForeground(PropertyLoader.LABEL_COLOR);
		
		if (Utils.cleanUpString(this.textArea.getText()).equalsIgnoreCase(
				Utils.cleanUpString(this.defaultString))) {
			this.textArea.setText(new String());
		}

		if (event.getSource().equals(PublicationMainPanel.titleField)) {
			PublicationMainPanel.blockForTextField();
		}
	}

	@Override
	public void focusLost(FocusEvent event) {

		if (Utils.checkIfStringIsEmpty(this.textArea.getText())) {
			this.textArea.setText(this.defaultString);
		}

		if (event.getSource().equals(PublicationMainPanel.titleField)) {

			try {

				PublicationFrame.getUserDirectory().getPrimaryDataEntity(
						((AttributeTextArea) event.getSource()).getText());

				Object[] options = { "Yes", "No" };
				int result = JOptionPane
						.showOptionDialog(
								PublicationModul.getFrame(),
								"Would you like to update the version? If not please change the title !",
								"Publication already exist !",
								JOptionPane.YES_NO_OPTION,
								JOptionPane.QUESTION_MESSAGE, null, options,
								options[0]);
				if (result == JOptionPane.YES_OPTION) {
					PublicationButtonLinePanel.updatePublicationFlag = true;
					PublicationMainPanel.releaseAllBlockedFields();

				}
				if (result == JOptionPane.NO_OPTION) {
					PublicationButtonLinePanel.updatePublicationFlag = false;
					PublicationMainPanel.releaseAllBlockedFields();
					((AttributeTextArea) event.getSource()).grabFocus();
				}

			} catch (RemoteException | PrimaryDataDirectoryException e) {

				PublicationMainPanel.releaseAllBlockedFields();

			}

		}
	}
}
